package com.jrx.anytxn.investor.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.common.uitl.BeanMapping;
import com.jrx.anytxn.i18n.response.TxnPage;
import com.jrx.anytxn.investor.entity.AmLoanMainInvestorInfo;
import com.jrx.anytxn.investor.entity.TlMistakeInvestorLog;
import com.jrx.anytxn.investor.entity.TlPaymentInvestorLog;
import com.jrx.anytxn.investor.mapper.ext.ExtAmLoanMainInvestorInfoMapper;
import com.jrx.anytxn.investor.mapper.ext.ExtTlMistakeInvestorLogMapper;
import com.jrx.anytxn.investor.mapper.ext.ExtTlPaymentInvestorLogMapper;
import com.jrx.anytxn.investor.service.IInvestorMistakeService;
import com.jrx.anytxn.investor.service.IInvestorPaymentService;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.bean.DealMistakeBean;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.dto.mistakeLog.MistakeLogRes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: anytxn-cf-transaction
 * @description: 差错处理操作类
 * @author: xiaoyu.jing
 * @date: 2019-10-24 09:50
 **/
@Service
public class InvestorMistakeServiceImpl implements IInvestorMistakeService {

    private static final Logger logger = LoggerFactory.getLogger(InvestorMistakeServiceImpl.class);

    @Autowired
    private ISegmentService segmentService;

    @Resource
    private ExtTlPaymentInvestorLogMapper extTlPaymentInvestorLogMapper;
    @Autowired
    private IInvestorPaymentService paymentService;
    @Resource
    private ExtTlMistakeInvestorLogMapper extTlMistakeInvestorLogMapper;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Resource
    private ExtAmLoanMainInvestorInfoMapper extAmLoanMainInvestorInfoMapper;


    /**
     * 处理差错记录
     *
     * @param bean
     * @throws Exception
     */
    @Override
    public void dealMistakeRecord(DealMistakeBean bean) throws Exception {
        Long recordId = bean.getId();
        String misType = bean.getMisType();
        String orgiSeqNo = bean.getOrgiSeqNo();
        String customerId = bean.getCustomerId();
        String tenantId = bean.getTenantId();
        String orgId = bean.getOrganizationId();
        PrOrganizationTable organization =
                organizationTableService.findByOrId(orgId, tenantId);
        Date bussinessDate = organization.getNextProcessingDate();
        if (TransBizConstant.MIS_TYPE_0.equals(misType)) {
            this.dealLoanMistakeRecord(recordId, orgiSeqNo, customerId, tenantId, bussinessDate);
        } else {
            this.dealRepayMistakeRecord(recordId, orgiSeqNo, customerId, tenantId, bussinessDate);
        }
    }

    @Override
    public TxnPage<MistakeLogRes> findMistakeLogByTenId(Integer pageNum, Integer pageSize, String tenantId) throws TxnBizException {
        Page<TlMistakeInvestorLog> page = PageHelper.startPage(pageNum, pageSize, Constant.ORDER_BY_SORT);
        List<TlMistakeInvestorLog> mistakeLogList = extTlMistakeInvestorLogMapper.selectByTenantId(tenantId);
        if (mistakeLogList.isEmpty()) {
            logger.error("查询差错流水记录列表为空");
            throw new TxnBizException(TxnRespCode.NO_DATA.getCode(), TxnRespCode.NO_DATA.getUserTips());
        }
        List<MistakeLogRes> res = BeanMapping.copyList(mistakeLogList, MistakeLogRes.class);
        return new TxnPage<>(pageNum, pageSize, page.getTotal(), res);
    }

    /**
     * 处理放款差错
     *
     * @param recordId
     * @param orgiSeqNo
     * @param customerId
     * @param tenantId
     * @throws Exception
     */
    private void dealLoanMistakeRecord(Long recordId, String orgiSeqNo, String customerId, String tenantId, Date bussinessDate) {

    }

    /**
     * 处理还款款差错
     *
     * @param recordId
     * @param orgiSeqNo
     * @param customerId
     * @param tenantId
     * @throws Exception
     */
    private void dealRepayMistakeRecord(Long recordId, String orgiSeqNo, String customerId, String tenantId, Date bussinessDate) throws Exception {
        List<TlMistakeInvestorLog> mistakeLogList = extTlMistakeInvestorLogMapper.selectMistake( customerId,
                tenantId, TransBizConstant.MIS_STATUS_0);
        List<TlMistakeInvestorLog> sortedMistakeLogList = mistakeLogList.stream().sorted(Comparator.comparing(TlMistakeInvestorLog::getCreateTime)).collect(Collectors.toList());
        if(!sortedMistakeLogList.get(0).getOrgiSeqNo().equals(orgiSeqNo)){
            throw new Exception("前置差错未处理完成");
        }
        TlPaymentInvestorLog log = extTlPaymentInvestorLogMapper.selectByPaymentSeqNo(orgiSeqNo, customerId, tenantId);
        List<AmLoanMainInvestorInfo> loanMainList = extAmLoanMainInvestorInfoMapper.findInvestorLoan(log.getLoanId(), log.getCustomerId(), log.getTenantId());
        paymentService.dealAllocation(log, loanMainList,bussinessDate);
        extTlMistakeInvestorLogMapper.updateMistake(recordId, customerId, tenantId,bussinessDate);
    }

    /**
     * 根据还款流水生成差错对象
     *
     * @param tlPaymentInvestorLog
     * @param bussinessDate
     * @return
     */
    @Override
    public TlMistakeInvestorLog buildMistakeLog(TlPaymentInvestorLog tlPaymentInvestorLog, Date bussinessDate) throws TxnBizException {
        TlMistakeInvestorLog log = new TlMistakeInvestorLog();
        try {
            log.setId(segmentService.getId(TransBizConstant.TL_MISTAKE_LOG_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }
        log.setTenantId(tlPaymentInvestorLog.getTenantId());
        log.setCustomerId(tlPaymentInvestorLog.getCustomerId());
        log.setOrganizationId(tlPaymentInvestorLog.getOrganizationId());
        log.setOrgiSeqNo(tlPaymentInvestorLog.getSeqNo());
        log.setMisType(TransBizConstant.MIS_TYPE_1);
        log.setMisStatus(TransBizConstant.MIS_STATUS_0);
        log.setMisAddDate(bussinessDate);
        log.setMisDealCount(0);
        log.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);
        log.setUpdateBy(TransBizConstant.SYS_OPRATE);
        return log;
    }


}
